<template>
  <div>
    <!-- 搜索条件 -->
    <el-card v-show="showQueryForm" class="form-card">
      <QueryForm ref="queryFormRef" :form-data="queryFormData" :model="queryFormData" :show-control="true" label-width="82px">
        <QueryFormItem label="字典标签" prop="dict_label">
          <el-input v-model="queryFormData.dict_label" placeholder="请输入字典标签"/>
        </QueryFormItem>

        <QueryFormItem label="字典键值" prop="dict_value">
          <el-input v-model="queryFormData.dict_value" placeholder="请输入字典键值"/>
        </QueryFormItem>

        <QueryFormItem label="是否启用" prop="enabled">
          <DictSelect v-model="queryFormData.enabled" dict-type="sys_enabled" placeholder="请选择"/>
        </QueryFormItem>

        <template #control>
          <el-button icon="Search" type="info" @click="handleSearch">{{ $t('form.search') }}</el-button>
          <el-button icon="Refresh" @click="handleResetQueryForm">{{ $t('form.reset') }}</el-button>
        </template>
      </QueryForm>
    </el-card>

    <!-- 列表数据 -->
    <el-card class="content-card">
      <!-- 工具栏 -->
      <table-toolbar v-model:columns="columns"
                     v-model:show-query-form="showQueryForm"
                     v-model:size="size"
                     v-model:stripe="stripe"
                     @refresh="handleSearch">
        <!-- 操作区域 -->
        <el-button v-permission="'sys:dict:create'" icon="CirclePlus" plain type="primary" @click="handleFormShow(1, 0)">新增</el-button>
      </table-toolbar>

      <!-- 列表记录 -->
      <div class="table-wrapper">
        <!-- 列表数据 -->
        <el-table ref="tableRef"
                  v-loading="loading"
                  :data="tableData"
                  :size="size"
                  :stripe="stripe"
                  row-key="id"
                  show-overflow-tooltip
                  @select="handleSelectChange"
                  @select-all="handleSelectAll"
                  @sort-change="handleSortChange">
          <template #empty>
            <el-empty class="table-empty" description="暂无数据"/>
          </template>

          <table-column :columns="columns">
            <template #enabled="scope">
              <DictTag v-model="scope.row.enabled" :circle="false" dict-type="sys_enabled" effect="plain"/>
            </template>

            <template #list_class="scope">
              <el-tag :type="scope.row.list_class">{{ scope.row.dict_label }}</el-tag>
            </template>

            <template #operations="scope">
              <el-button v-permission="'sys:dict:update'" link type="primary" @click="handleFormShow(2, scope.row.id)">编辑</el-button>
              <el-button v-permission="'sys:dict:delete'" link type="danger" @click="handleDeleteByRow(scope.row)">删除</el-button>
            </template>
          </table-column>
        </el-table>

        <!-- 分页操作 -->
        <el-pagination v-if="totalCount > 0"
                       :current-page="pageQuery.pageNum"
                       :page-size="pageQuery.pageSize"
                       :page-sizes="pageSizes"
                       :total="totalCount"
                       background
                       class="table-pagination"
                       layout="total, sizes, prev, pager, next"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </el-card>

    <!-- 添加或修改 -->
    <OperateForm :dict-type-id="props.id" ref="formRef" @success="handleSearch"/>
  </div>
</template>

<script lang="tsx" setup>
import { computed, h, onBeforeMount, reactive, ref } from 'vue';
import { QueryForm, QueryFormItem } from '@/components/query-form';
import useLoading from '@/hooks/use-loading';
import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
import TableToolbar from '@/components/table-toolbar/index.vue';
import useTableSelection from '@/hooks/use-table-selection';
import { ElMessageBox, ElNotification, TableInstance } from 'element-plus';
import useTable from '@/hooks/use-table.ts';
import { sysDictDataDelete, sysDictDataList } from '@/api/api-sys.ts';
import { hasPermission } from '@/utils/permission.ts';
import OperateForm from './dict-data-form.vue';
import { computedOperateWidth } from '@/utils';
import { DictTag } from '@/components/dict-tag';
import { DictSelect } from '@/components/dict-select';

defineOptions({name: 'sys-dict-data'});

const props = defineProps({
  id: {
    type: Number,
    default: 0
  },
});

// 查询
const queryFormData = reactive({
  dict_type_id: undefined,
  dict_label: undefined,
  dict_value: undefined,
  enabled: undefined,
});
const queryFormRef = ref<InstanceType<typeof QueryForm>>();

const tableRef = ref<TableInstance>();
const tableData = ref<any[]>([]);
const totalCount = ref(0);

// 操作区域宽度计算
const operateWidth = computed(() => {
  let count = 0
  if (hasPermission('sys:dict:update')) count += 1
  if (hasPermission('sys:dict:delete')) count += 1
  return computedOperateWidth(count);
})

// 列设置
const columns = ref<TableColumnData[]>([
  {prop: 'id', label: '编号', width: 105, align: 'center', sortable: 'custom'},
  {prop: 'dict_name', label: '字典', minWidth: 160, align: 'center',},
  {prop: 'dict_label', label: '标签', minWidth: 160, align: 'center', sortable: 'custom'},
  {prop: 'dict_value', label: '键值', minWidth: 160, align: 'center', sortable: 'custom'},
  {prop: 'list_class', label: '回显', minWidth: 160, align: 'center', sortable: 'custom'},
  {prop: 'enabled', label: '状态', minWidth: 110, align: 'center', sortable: 'custom'},
  {prop: 'order_num', label: '排序', minWidth: 110, align: 'center', sortable: 'custom'},
  {prop: 'remark', label: '备注', minWidth: 200, align: 'center', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'create_time', label: '创建时间', width: 180, align: 'center', sortable: 'custom'},
  {prop: 'update_time', label: '修改时间', width: 180, align: 'center', sortable: 'custom'},
]);

onBeforeMount(() => {
  if (operateWidth.value > 0) {
    columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'left', headerAlign: 'center'},)
  }
});

const [loading, setLoading] = useLoading(false);
const {tableMethods, tableState} = useTable(() => fetchDataList(), queryFormRef, true);
const {size, stripe, showQueryForm, pageQuery, pageSizes} = tableState
const {handleSizeChange, handleCurrentChange, handleSortChange, handleResetForm} = tableMethods
const {handleSelectChange, handleSelectAll, multipleSelection} = useTableSelection(tableData, tableRef);

// 数据查询
const fetchDataList = async () => {
  setLoading(true);
  try {
    // @ts-ignore
    queryFormData.dict_type_id = props.id || undefined;
    // 查询数据
    const {data} = await sysDictDataList({
      page_num: pageQuery.pageNum,
      page_size: pageQuery.pageSize,
      order_mode: pageQuery.orderMode,
      order_column: pageQuery.orderColumn,
      ...queryFormData,
    });
    // 结果转换
    tableData.value = data.list;
    totalCount.value = data.pages.total_count;
  } catch (err) {
  } finally {
    setLoading(false);
  }
};

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

// 对外提供调用方法
defineExpose({handleSearch})

// 重置查询条件
const handleResetQueryForm = () => {
  // @ts-ignore
  queryFormData.dict_type_id = props.id || undefined;
  handleResetForm();
};

/** 添加/修改操作 */
const formRef = ref<any>()
const handleFormShow = (mode: number, id?: number) => {
  formRef.value?.open(mode, id)
};

const handleDeleteByRow = ({id, dict_label}) => {
  ElMessageBox({
    title: '删除确定',
    message: h('p', null, [
      '您确定要删除字典标签 ',
      h('span', {style: 'font-weight: bold'}, dict_label),
      ' ？',
    ]),
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then((action) => {
    sysDictDataDelete(id).then(() => {
      ElNotification({title: '成功', message: '删除成功', type: 'success', duration: 2000})
      handleSearch();
    })
  });
};
</script>

<style lang="scss" scoped>

</style>
